#include "../src/IoComm.h"
#include "../src/IoComm_CommandHandler.h"
#include "../src/CommandHandler.h"
#include "../src/PanelComm.h"
#include "../src/Common.h"
#include "../src/Framework.h"
#include "stdio.h"

static void HandleIoCommCommand(void);
static void HandleIoCommRply(uint8_t cmd);

void IoComm_CommandHandler_Execute(void) {
    if (IoComm_ChkAndClearPackValidFlag()) {
        HandleIoCommCommand();
    }
}

static void HandleIoCommCommand(void) {
    uint8_t cmd = IoCommRecPacket.Members.Cmd;
    HandleIoCommRply(cmd);
}

static void HandleIoCommRply(uint8_t cmd) {
    switch (cmd) {
        case READ_VER_INFO_SPI: {   //0xC1
            PanelCommRplyPacket.Cmd = READ_VER_INFO_BACK;   //0xF4

            char strBuf[21];
            int strLen;
            strLen = snprintf(strBuf, 21, BOOT_VER_FORMAT, GetSlaveNum(), IoCommRecPacket.Members.Data[0], IoCommRecPacket.Members.Data[1], IoCommRecPacket.Members.Data[2], IoCommRecPacket.Members.Data[3]);
            
            PanelCommRplyPacket.DataByteLength = strLen;
            int i;
            for (i = 0; i < strLen; i++)
            {
                PanelCommRplyPacket.Data[i] = strBuf[i];
            }

            break;
        }
        
        case SET_MODE_SPI: {     //0x42
            return;
        }
        
        case ERASE_FLASH_UART_BACK: {   //0xC3
            PanelCommRplyPacket.Cmd = ERASE_FLASH_BACK; //0xF6
            PanelCommRplyPacket.Data[0] = IoCommRecPacket.Members.Data[0];
            PanelCommRplyPacket.DataByteLength = 1;
            break;
        }
        
        case PROGRAM_FLASH_UART_BACK: {  //0xC4
            PanelCommRplyPacket.Cmd = PROGRAM_FLASH_BACK;   //0xF7
            PanelCommRplyPacket.Data[0] = IoCommRecPacket.Members.Data[0];
            PanelCommRplyPacket.DataByteLength = 1;
            break;
        }
        
        case CHECK_CRC_UART_BACK: {  //0xC5
            PanelCommRplyPacket.Cmd = CHECK_CRC_BACK;   //0xF8
            PanelCommRplyPacket.Data[0] = IoCommRecPacket.Members.Data[0];
            PanelCommRplyPacket.DataByteLength = 1;
            break;
        }
        
        default:
            return;
    }
    
    PopulateRplyPack();
    PanelComm_FillTxBytesWithRplyPack();
}